#!/usr/bin/env python
# -*- coding: utf-8 -*-
# =================================================
# @File    : mysqldriver
# @IDE     : PyCharm
# @Author  : Liu Xian Gui
# @Date    : 2024/3/26 21:41
# @Describe: 
# ==================================================
import json
import pymysql
from config.common_config import db_mysql_info
from library.log import logger


def sql_data_to_dict(data):
    for item in data:
        for key, value in item.items():
            if isinstance(value, str):
                try:
                    _value = json.loads(value)
                    if isinstance(_value, list) or isinstance(_value, dict):
                        item[key] = _value
                except Exception as e:
                    print(value)
                    logger.error(e)


db = db_mysql_info


class MysqlDriver(object):
    def __init__(self):
        self.host = db.get("host")
        self.port = db.get("port")
        self.user = db.get("user")
        self.pwd = db.get("pwd")
        self.database = db.get("database")

    def connect(self):
        self.db = pymysql.connect(
            host=self.host,
            port=self.port,
            password=self.pwd,
            user=self.user,
            db=self.database,
            charset="utf8mb4",
            cursorclass=pymysql.cursors.DictCursor,
            connect_timeout=100,
            read_timeout=100
        )

    def execute(self, sql) -> bool:
        try:
            self.connect()
            cursor = self.db.cursor()
            cursor.execute(sql)
            self.db.commit()
            return True
        except Exception as e:
            self.db.rollback()
            logger.error(e)
            return False

    def query(self, sql, is_to_dict=True):
        try:
            self.connect()
            cursor = self.db.cursor()
            cursor.execute(sql)
            data = cursor.fetchall()
            if is_to_dict:
                sql_data_to_dict(data)
            return data
        except Exception as e:
            logger.error(e)
        finally:
            self.close()

    def close(self):
        self.db.close()

if __name__ == '__main__':
    db_obj = MysqlDriver()
    data = db_obj.query(sql="select * from student_info", is_to_dict=True)
    print(data)
    print(type(data))